//
//  HTClassSearchVC.swift
//  QuitSmokingApp
//
//  Created by   on 2024/3/13.
//

import UIKit
import Combine

class HTClassSearchVC: HTClassViewController {
    lazy var var_SearchTF: UITextField = {
        let var_textF = UITextField()
        var_textF.textColor = .black
        var_textF.textAlignment = .left
        var_textF.font = .systemFont(ofSize: 14, weight: .medium)
        return var_textF
    }()
    
    lazy var var_search_view: UIView = {
        let var_view = UIView()
        var_view.backgroundColor = .white
        var_view.layer.cornerRadius = 15.auto()
        var_view.layer.masksToBounds = true
        
        
        
        
        let var_search_icon = UIButton()
        var_search_icon.setImage(UIImage(named: "icon_search"), for: .normal)
        var_view.addSubview(var_search_icon)
        var_search_icon.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-4.auto())
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20.auto())
        }
        
        var_view.addSubview(var_SearchTF)
        var_SearchTF.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15.auto())
            make.right.equalTo(var_search_icon.snp.left).offset(-15.auto())
            make.top.bottom.equalToSuperview()
        }
       
        return var_view
    }()
    lazy var var_bgView: UIView = {
        let var_view = UIView()
        var_view.backgroundColor = .black
        return var_view
    }()
    lazy var var_brandArray: [String: HTClassSearchModel] = {
        return [
            "Marlboro": HTClassSearchModel(var_name: "Marlboro", var_price: "8"),
            "Newport": HTClassSearchModel(var_name: "Newport", var_price: "9"),
            "Camel": HTClassSearchModel(var_name: "Camel", var_price: "8"),
            "Winston": HTClassSearchModel(var_name: "Winston", var_price: "8"),
            "Pall Mall": HTClassSearchModel(var_name: "Pall Mall", var_price: "7"),
            "L&M": HTClassSearchModel(var_name: "L&M", var_price: "7"),
            "American Spirit": HTClassSearchModel(var_name: "American Spirit", var_price: "10"),
            "Parliament": HTClassSearchModel(var_name: "Parliament", var_price: "9"),
            "Kool": HTClassSearchModel(var_name: "Kool", var_price: "8"),
            "Doral": HTClassSearchModel(var_name: "Doral", var_price: "7")
        ]
    }()
    lazy var var_tableView: UITableView = {
        let var_tab = UITableView(frame: .zero, style: .plain)
        var_tab.bounces = false
        var_tab.dataSource = self
        var_tab.delegate = self
        var_tab.backgroundColor = .clear
        var_tab.register(HTClassSearchCell.self, forCellReuseIdentifier: "HTClassSearchCell")
        return var_tab
    }()
    private var var_cancellable: AnyCancellable?
    var var_dataSource: [HTClassSearchModel] = []
    lazy var var_noDataView: UILabel = {
        let var_label = UILabel()
        var_label.textColor = .white
        var_label.font = .systemFont(ofSize: 14)
        var_label.text = "No search results found."
        return var_label
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
        self.navigationController?.navigationBar.addSubview(var_search_view)
        var_search_view.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(47.auto())
            make.right.equalToSuperview().offset(-15.auto())
            make.centerY.equalToSuperview()
            make.height.equalTo(30.auto())
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        var_search_view.removeFromSuperview()
    }
    override func ht_setUI() {
        super.ht_setUI()
        view.addSubview(var_bgView)
        var_bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(HTClassTool.STATIC_navigationBarTotalHeight)
        }
        
       
//        
//        // 订阅文本输入的变化，并进行节流处理
        var_cancellable = NotificationCenter.default
            .publisher(for: UITextField.textDidChangeNotification, object: var_SearchTF)
            .map { ($0.object as? UITextField)?.text ?? "" }
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
            .sink {[weak self] var_text in
                guard let self = self else { return }
                let var_result = var_text.lowercased()
                let var_key = Array(self.var_brandArray.keys)
                let var_filteredCigarettes = var_key.filter { $0.lowercased().contains(var_result) }
                var var_array: [HTClassSearchModel] = []
                for var_item in var_filteredCigarettes {
                    if let var_model = self.var_brandArray[var_item] {
                        var_array.append(var_model)
                    }
                }
                self.var_dataSource = var_array
                self.reloadData()
            }
//        
        var_bgView.addSubview(self.var_tableView)
        var_tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(10)
        }
        
        var_bgView.addSubview(var_noDataView)
        var_noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        var_noDataView.isHidden = true
    }
    
    deinit {
        var_cancellable?.cancel()
    }
    
    func reloadData() {
        if self.var_dataSource.count > 0 {
            self.var_tableView.isHidden = false
            self.var_noDataView.isHidden = true
            self.var_tableView.reloadData()
        } else {
            self.var_tableView.isHidden = true
            self.var_noDataView.isHidden = false
        }
        
    }
}

extension HTClassSearchVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return -1
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return var_dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView(frame: CGRect(x: 0, y: 0, width: HTClassTool.STATIC_screenWidth, height: 10))
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HTClassSearchCell", for: indexPath) as! HTClassSearchCell
        let var_model = var_dataSource[indexPath.section]
        cell.var_nameLabel.text = var_model.var_name
        cell.var_priceLabel.text = "$\(var_model.var_price)"
        return cell
    }
}
